package br.net.cep.util.net;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.net.cep.util.db.ConexaoDB;
import wsl.controle.Controlador;

/**
 * Servlet implementation class Ws
 */
public class Ws extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Ws() {
        super();
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        String msg = "";
        String rs = "null";        
        String servico = request.getParameter("s");
        String id =  request.getParameter("id");
        msg = "{\"id\":"+id+",\"s\":\""+servico+"\",\"rs\":";
        String realPath = getServletContext().getRealPath("/");
        Controlador.getInstancia().setConfig(realPath+getInitParameter("config"));
        try {
        	out = response.getWriter();            
        	ConexaoDB.iniciarSessao();
        	rs = Controlador.getInstancia().deployWS(servico,request.getParameterValues("p"));
        	ConexaoDB.fecharSesssao();
        } catch (Exception ex) {
            Controlador.getInstancia().addErro(ex.getMessage().toString());
        }finally{
        	msg += rs;
            msg += ",\"erro\":"+Controlador.getInstancia().errosToString()+"}";
            out.print(msg);
            out.close();
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    public String getServletInfo() {
        return "Short description";
    }
}
